import React, { Component } from "react";
// 引入store, 用于获取redux中保存的状态
import store from "../../redux/store";

export default class Count extends Component {

    state = {
      num: 0
    }
    componentDidMount(){
      // 检测redux中状态的变化，只要变化，就调用render
      store.subscribe(() => {
        //  this.forceUpdate()
         this.setState({})
      })
    }
    increment = () => {
        // const {num} = this.state
        // this.setState({
        //   num: num + Number(this.selectNumber.value)
        // })
       store.dispatch({type:'increment', data: Number(this.selectNumber.value)})
    }
    decrement = () => {
      // const {num} = this.state
      // this.setState({
      //   num: num - Number(this.selectNumber.value)
      // })      
      store.dispatch({type:'decrement', data: Number(this.selectNumber.value)})
    }
    incrementIfOdd = () => {
        // const {num} = this.state
        // if (num%2 === 1) {
        //   this.setState({
        //     num: num + Number(this.selectNumber.value)
        //   }) 
        // }
        const num = store.getState()
        if (num%2 === 1) {
          store.dispatch({type:'increment', data: Number(this.selectNumber.value)})
        }
      }
    incrementAsync = () => {
      // const {num} = this.state
      //  setTimeout(() => {
      //   this.setState({
      //     num: num + Number(this.selectNumber.value)
      //   })
      //  }, 500)

      setTimeout(() => {
        store.dispatch({type:'increment', data: Number(this.selectNumber.value)})
      }, 500)
      }

    render() {
        return (
            <div>
               <h2>当前求和为：{store.getState()}</h2>
               <div>
                   <select ref={c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                   </select>
                   <button onClick={this.increment}>+</button>
                   <button onClick={this.decrement}>-</button>
                   <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
                   <button onClick={this.incrementAsync}>异步加</button>
                </div>
            </div>
        )
    }
}